import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter/material.dart';
import '../providers/route_provider.dart';
import '../pages/with_params_page.dart';
import '../pages/home_page.dart';

/// GoRouter 配置的 Provider
final routerProvider = Provider<GoRouter>((ref) {
  final routeItems = ref.watch(routeItemsProvider);

  return GoRouter(
    initialLocation: '/',
    routes: [
      // 首页路由
      GoRoute(
        path: '/',
        builder: (context, state) => const HomePage(),
      ),
      // 动态生成其他路由
      ...routeItems.map((routeItem) {
        if (routeItem.path.contains(':')) {
          // 带参数的路由
          return GoRoute(
            path: routeItem.path,
            builder: (context, state) {
              final title = state.pathParameters['title'] ?? '默认标题';
              final description = state.uri.queryParameters['description'];
              final countStr = state.uri.queryParameters['count'];
              final count = countStr != null ? int.tryParse(countStr) : null;
              
              return WithParamsPage(
                title: title,
                description: description,
                count: count,
              );
            },
          );
        } else {
          // 无参数的路由
          return GoRoute(
            path: routeItem.path,
            builder: (context, state) => routeItem.page,
          );
        }
      }).toList(),
    ],
  );
});
